// 本地存储

package storage

import (
	"fmt"
	"io/ioutil"
	"os"
	"path"
	"path/filepath"
)

type (
	// LocalStorage struct
	LocalStorage struct {
		StoragePath string
	}
)

func init() {
	Register("local", NewLocalStorage())
}

// NewLocalStorage function
// Generate LocalStorage struct Type
func NewLocalStorage() *LocalStorage {
	return &LocalStorage{}
}

// Get Function
//获得图片
func (ls *LocalStorage) Get(src string) ([]byte, error) {
	return fileGetContents(src)
}

// Save function
//存储图片
func (ls *LocalStorage) Save(src string, imageData []byte) error {
	var err error
	if ls.IsExist(src) {
		err = fmt.Errorf("This save file is exist: %s", src)
	} else {
		err = filePutContents(src, imageData)
	}
	return err
}

// Delete function
// 删除图片
func (ls *LocalStorage) Delete(src string) error {
	return os.Remove(ls.makefilePath(src))
}

// IsExist function
// 检查文件是否存在
func (ls *LocalStorage) IsExist(src string) bool {
	_, err := os.Stat(ls.makefilePath(src))
	if err != nil && os.IsNotExist(err) {
		return false
	}
	return true
}

// fileGetContents func
// 读文件
func fileGetContents(fileName string) ([]byte, error) {
	fd, err := os.Open(new(LocalStorage).makefilePath(fileName))
	if err != nil {
		return nil, err
	}
	defer fd.Close()
	imageData, err := ioutil.ReadAll(fd)
	if err != nil {
		return nil, err
	}
	return imageData, nil
}

// filePutContents function
// 写文件
func filePutContents(filename string, content []byte) error {
	err := os.MkdirAll(path.Dir(filename), os.ModePerm)
	if err != nil {
		return err
	}
	return ioutil.WriteFile(filename, content, 0655)
}

//存储文件路径
//@return ls.StoragePath＋"/"＋src
func (ls *LocalStorage) makefilePath(src string) string {
	return filepath.Join(ls.StoragePath, src)
}
